package com.lilinling.yinzhi.gateway.filter;

import com.google.gson.JsonObject;
import com.lilinling.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

//@Component
//public class AuthMakerFilter implements GlobalFilter, Ordered {
//
//    @Autowired
//    AuthGlobalFilter authGlobalFilter;
//
//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        ServerHttpRequest request = exchange.getRequest();
//        String path = request.getURI().getPath();
//
//        AntPathMatcher antPathMatcher = new AntPathMatcher();
//        if (antPathMatcher.match("/api/**/authmaker/**",path)) {
//
//            //获取token
//            List<String> tokenList = request.getHeaders().get("token");
//            Long makerId = JwtUtils.getUserIdByJwtToken(tokenList.get(0)).getMakerId();
//            if (makerId == null) {
//                ServerHttpResponse response = exchange.getResponse();
//                return noMaker(response);
//            }
//        }
//        //放行
//        return chain.filter(exchange);
//    }
//
//    @Override
//    public int getOrder() {
//        return 1;
//    }
//
//    /**
//     * 使用webflux输入请求信息
//     */
//    private Mono<Void> noMaker(ServerHttpResponse response) {
//        JsonObject message = new JsonObject();
//        message.addProperty("success",false);
//        message.addProperty("code",10888);
//        message.addProperty("data","");
//        message.addProperty("msg","未成为制作人");
//        byte[] bytes = message.toString().getBytes(StandardCharsets.UTF_8);
//        DataBuffer buffer = response.bufferFactory().wrap(bytes);
//        //指定编码
//        response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
//        //输出http响应
//        return response.writeWith(Mono.just(buffer));
//    }
//}
